package Q2;

import java.util.LinkedList;
import java.util.Queue;

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 判断岛屿数量
     * @param grid char字符型二维数组
     * @return int整型
     */

    public static int sum;
    public static int n;
    public static int[] dx = {0, 0, 1, -1};
    public static int[] dy = {1, -1, 0, 0};
    public static boolean[][] flag;
    public static Queue<int[]> queue = new LinkedList<>();

    public static int solve (char[][] grid) {
        // write code here

        n = grid.length;
        flag = new boolean[n][n];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1') {
                    queue.offer(new int[]{i, j});
                }
            }
        }

        int ret = 0;
        while (!queue.isEmpty()) {
            Queue<int[]> queue1 = new LinkedList<>();
            int[] arr = queue.poll();
            if (!flag[arr[0]][arr[1]]) {
                ret++;
                queue1.offer(arr);
                while (!queue1.isEmpty()) {
                    int[] arr1 = queue1.poll();
                    int x = arr1[0];
                    int y = arr1[1];
                    flag[x][y] = true;
                    for (int i = 0; i < 4; i++) {
                        int xx = x + dx[i];
                        int yy = y + dy[i];
                        if (xx >= 0 && xx < n && yy >= 0 && yy < n && !flag[xx][yy] && grid[xx][yy] == '1') {
                            flag[xx][yy] = true;
                            queue1.offer(new int[]{xx, yy});
                        }
                    }
                }
            }
        }

        return ret;
    }

    public static void main(String[] args) {
        System.out.println(solve(new char[][]{{0}}));
    }
}